#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <opencv2/opencv.hpp>

#include <QFileDialog>
#include <QDebug>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QMimeData>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->label->setScaledContents(true);
    setAcceptDrops(true);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    auto fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), "/home/jake/Picture", "Images(*.png *.jpg *.jpeg)");
    if (fileName.isEmpty()) {
        return;
    }
    open_image(fileName);
}

void MainWindow::dragEnterEvent(QDragEnterEvent *e)
{
    qDebug("%s(%s)[%d]", __FILE__, __func__, __LINE__);
    e->acceptProposedAction();
}

void MainWindow::dropEvent(QDropEvent *e)
{
    qDebug() <<e->mimeData()->formats();
    open_image(e->mimeData()->urls().first().toLocalFile());
}

void MainWindow::open_image(const QString &fileName)
{
    qDebug() << fileName;

    auto mat = cv::imread(fileName.toStdString());
    if (mat.empty()) {
        return;
    }
    auto image = QImage((const unsigned char*)(mat.data), mat.cols, mat.rows, mat.step, QImage::Format_BGR888);
    ui->label->setPixmap(QPixmap::fromImage(image));
}
